package com.ml.shs.repository;

import com.ml.shs.entity.Goods;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Repository
public class PhotoRepository {

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Resource
    private GridFSBucket gridFSBucket;

    public String save(InputStream is,String fileName) {
        ObjectId id = gridFsTemplate.store(is, fileName, "image");
        return id.toString();
    }

    public GridFsResource findPhoto(String fileId){

        GridFSFile gridFsFile =  gridFsTemplate.findOne(new Query(Criteria.where("_id").is(fileId)));
        GridFsResource resource =  gridFsTemplate.getResource(gridFsFile);

        return resource;
    }

    public void deletePhoto(String fileId) {
        gridFsTemplate.delete(new Query(Criteria.where("_id").is(fileId)));
    }
}
